package com.jeecg.p3.system.web.back;

import cn.hutool.Hutool;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import com.jeecg.p3.base.util.ComCode;
import com.jeecg.p3.base.util.DateUtil;
import com.jeecg.p3.base.util.WxUserInfo;
import com.jeecg.p3.base.util.WxUtils;
import com.jeecg.p3.system.advisor.entity.StudyAdviser;
import com.jeecg.p3.system.advisor.service.StudyAdvService;
import com.jeecg.p3.system.entity.JwSystemUser;
import com.jeecg.p3.system.service.JwSystemAuthService;
import com.jeecg.p3.system.service.JwSystemUserService;
import com.jeecg.p3.system.service.JwWebJwidService;
import com.jeecg.p3.system.util.Constants;
import com.jeecg.p3.system.vo.LoginUser;
import com.jeecg.p3.system.vo.Menu;
import com.jeecg.p3.system.vo.WeixinAccountDto;
import org.apache.velocity.VelocityContext;
import org.jeecgframework.p3.core.common.utils.AjaxJson;
import org.jeecgframework.p3.core.util.plugin.ViewVelocity;
import org.jeecgframework.p3.core.utils.common.StringUtils;
import org.jeecgframework.p3.core.web.BaseController;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("/system/back/wx")
public class WxAuthController extends BaseController {
    public static final Logger logger = LoggerFactory.getLogger(WxAuthController.class);

    public final static String indexPath = "base/back/hplus/index.vm";
    @Autowired
    private StudyAdvService advService;
    @Autowired
    private JwSystemUserService jwSystemUserService;
    @Autowired
    private JwWebJwidService jwidService;
    @Autowired
    private JwSystemAuthService jwSystemAuthService;


    /**
     * 获取用户微信信息
     * @param request
     * @param response
     * @param model
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "/getCode",method ={RequestMethod.GET, RequestMethod.POST})
    public void getCode(HttpServletRequest request, HttpServletResponse response, ModelMap model) throws Exception{
        try {
            VelocityContext velocityContext = new VelocityContext();
            String uid = request.getParameter("uid");
            log.info("uid----->" + uid);
            String wxId = request.getParameter("wxId");
            JwSystemUser user = jwSystemUserService.queryById(Long.valueOf(uid));
            if(!Constants.stateActvi.equals(user.getState())) {
                AjaxJson j = WxUtils.getWxUserDetail(request);
                if(j.isSuccess()) {
                    WxUserInfo wxUserInfo = (WxUserInfo) j.getObj();
                    StudyAdviser adviser = advService.findByUserNumber(user.getUserId());
                    adviser.setNickName(wxUserInfo.getNickname());
                    adviser.setSex(wxUserInfo.getSex());
                    adviser.setOpenId(wxUserInfo.getOpenid());
                    adviser.setPhoto(wxUserInfo.getHeadimgurl());
                    adviser.setEntryTime(DateUtil.dateToString(new Date(), "yyyy-MM-dd HH:mm:ss"));
                    adviser.setWxId(wxId);
                    advService.update(adviser, Long.valueOf(uid));
                } else {
                    String viewName = "base/back/common/error.vm";
                    ViewVelocity.view(request, response, viewName, velocityContext);
                }
            } else {
                logger.info("已经完成顾问激活！");
            }

            String viewName = "base/back/common/login.vm";
            List<WeixinAccountDto> jwids = jwidService.queryJwWebJwidByUserId(user.getUserId());
            if(jwids != null && jwids.size() >0) {
                LoginUser loginUser = jwSystemUserService.queryUserByUserId(user.getUserId());
                request.getSession().setAttribute(Constants.SYSTEM_JWID, jwids.get(0).getJwid());
                request.getSession().setAttribute(Constants.SYSTEM_JWIDNAME, jwids.get(0).getName());
                request.getSession().setAttribute(Constants.SYSTEM_USERID, user.getUserId());
                request.getSession().setAttribute(Constants.OPERATE_WEB_LOGIN_USER, loginUser);
                velocityContext.put("jwidname", jwids.get(0).getName());
                velocityContext.put("userid", user.getUserId());
                try {
                    // 获取菜单
                    List<Menu> menuTree = jwSystemAuthService.getMenuTree(user.getUserId());
                    velocityContext.put(Constants.OPERATE_WEB_MENU_TREE, menuTree);
                    viewName = indexPath;
                    ViewVelocity.view(request, response, viewName, velocityContext);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
